package bb.lanxing.util;

import static bb.lanxing.util.InstallerUtil.APP_QQ;
import static bb.lanxing.util.InstallerUtil.APP_QZONE;
import static bb.lanxing.util.InstallerUtil.APP_SINA;
import static bb.lanxing.util.InstallerUtil.APP_WECHAT;
import static bb.lanxing.view.ShareView.TYPE_OTHER;
import static bb.lanxing.view.ShareView.TYPE_QQ;
import static bb.lanxing.view.ShareView.TYPE_QZONE;
import static bb.lanxing.view.ShareView.TYPE_WECHAT;
import static bb.lanxing.view.ShareView.TYPE_WEIBO;
import static bb.lanxing.view.ShareView.TYPE_WX_CIRCLE;

import java.io.File;
import java.text.MessageFormat;

import com.github.mikephil.charting.utils.Utils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.open.SocialConstants;
import com.tencent.tauth.Tencent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMMin;
import com.umeng.socialize.media.UMWeb;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.Toast;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.ali.behavior.AppBehavior;
import bb.lanxing.common.config.Constants;
import bb.lanxing.model.database.IWorkout;
import bb.lanxing.model.database.RouteBook;
import bb.lanxing.model.database.Workout;
import bb.lanxing.net.ApiClientConfigs;
import bb.lanxing.network.MyHttpClient;

public class CustomShareUtil {
    private static final String BASE_URL_ROUTE;
    private static final String BASE_URL;
    private static final String CONTENT_DETAIL =
            "我的路，有汗水，有微笑，也有蓝行。{0}{1,number,#.##}km，用时{2}，均速{3,number,#.##}km/h，消耗{4}kcal，使用@蓝行骑行软件 记录，";
    private static final String CONTENT_DETAIL_QZONE =
            "{0}{1,number,#.##}km，用时{2}，均速{3,number,#.##}km/h，消耗{4}kcal，使用@蓝行骑行软件 记录，";
    private static final String CONTENT_SIMPLE = "我的路，有汗水，有微笑，也有蓝行。@蓝行骑行软件，";
    private static final String CONTENT_URL_ROUTE;
    private static final String CONTENT_URL;
    private static final String CONTENT_WEIBO_TOPIC = "%s@蓝行骑行软件，详情请点击：%s";

    private static final String SHARE_URL_LUSHU_COLLECTION;

    private static final String TITLE_WORKOUT = "使用蓝行记录";
    private static final String TYPE_CYCLING = "骑行";
    private static final String TYPE_DEFAULT = "运动";
    private static final String TYPE_RUNNING = "跑步";
    private static final String TYPE_WALKING = "徒步";

    static {
        if (MyHttpClient.DOMAIN_BASE == null) {
            MyHttpClient.initDomain();
        }
        String str = ApiClientConfigs.PROTOCOL_HTTP + MyHttpClient.DOMAIN_BASE;
        BASE_URL = str;
        String str2 = ApiClientConfigs.PROTOCOL_HTTP + MyHttpClient.DOMAIN_BASE + "/xing/";
        BASE_URL_ROUTE = str2;
        CONTENT_URL = "点击进入官网：" + str;
        CONTENT_URL_ROUTE = "点击查看轨迹详情：" + str2;

        StringBuilder sb = new StringBuilder();
        sb.append("https://");
        sb.append(MyHttpClient.DOMAIN_BASE);
        SHARE_URL_LUSHU_COLLECTION = ApiClientConfigs.PROTOCOL_HTTP + MyHttpClient.DOMAIN_BASE + "/lushu_collection/";
    }

    private static boolean checkAppInstalled(Activity activity, int shareType) {
        if (shareType == TYPE_QQ) {
            Tencent.setIsPermissionGranted(true);
            if (!InstallerUtil.isAppInstalled(activity, APP_QQ)) {
                App.getContext().showMessage("您还未安装QQ客户端");
                return false;
            }
        } else if (shareType != TYPE_QZONE) {
            if (shareType == TYPE_WECHAT || shareType == TYPE_WX_CIRCLE) {
                if (!InstallerUtil.isAppInstalled(activity, APP_WECHAT)) {
                    App.getContext().showMessage("您还未安装微信客户端");
                    return false;
                }
            } else if (shareType == TYPE_WEIBO && !InstallerUtil.isAppInstalled(activity, APP_SINA)) {
                App.getContext().showMessage("您还未安装新浪微博客户端");
                return false;
            }
        } else if (!InstallerUtil.isAppInstalled(activity, APP_QZONE)) {
            App.getContext().showMessage("您还未安装QQ空间客户端");
            return false;
        }
        return true;
    }

    public static void shareLuShu(Activity activity, RouteBook routeBook, int shareType) {
        String str;
        UMImage uMImage;
        if (checkAppInstalled(activity, shareType) && routeBook != null) {
            if (TextUtils.isEmpty(routeBook.getTitle())) {
                str = "";
            } else {
                str = "路书：" + routeBook.getTitle();
            }
            String title = str;
            String description = String.format("%s", "全程距离：" + (routeBook.getDistance() / 1000.0d) + "km\n创建人：" + routeBook.getUsername());
            String imageUrl = routeBook.getImageUrl();
            String url = imageUrl;
            if (!TextUtils.isEmpty(imageUrl) && imageUrl.startsWith("http") || imageUrl.startsWith("https")) {
                uMImage = new UMImage(activity, imageUrl);
            } else {
                uMImage = new UMImage(activity, (int) R.drawable.ic_default);
            }
            if (shareType == TYPE_QQ) {
                Tencent.setIsPermissionGranted(true);
                shareUrlByUmeng(activity, title, description, url, uMImage, shareType);
            } else if (shareType == TYPE_QZONE) {
                shareUrlByUmeng(activity, title, description, url, uMImage, shareType);
            } else if (shareType == TYPE_WECHAT) {
                shareUrlByUmeng(activity, title + "\n" + description, description, url, uMImage, shareType);
            } else if (shareType == TYPE_WX_CIRCLE) {
                shareUrlByUmeng(activity, title + "\n" + description, description, url, uMImage, shareType);
            } else if (shareType == TYPE_WEIBO) {
                shareUrlByUmeng(activity, title, String.format(CONTENT_WEIBO_TOPIC, description, url), url, uMImage,
                        shareType);
            } else if (shareType == TYPE_OTHER) {
                shareOthers(activity, buildTextIntent(title, String.format(CONTENT_WEIBO_TOPIC, description, url)));
            }
            AppBehavior.shareBehavior(shareType, AppBehavior.route(), String.valueOf(routeBook.getServerId()));
        }
    }

    public static void shareImage(Activity activity, Bitmap b, int shareType) {
        if (checkAppInstalled(activity, shareType)) {
            if (shareType == 0) {
                shareImageByUmeng(activity, b, null, shareType);
            } else if (shareType == 2 || shareType == 3) {
                shareToWeixin(b, shareType == 3);
            }
        }
    }

    public static void shareWebUrl(Activity activity, String title, String content, String thumb_url, String url,
            int shareType) {
        UMImage uMImage;
        if (checkAppInstalled(activity, shareType)) {
            if (thumb_url != null) {
                uMImage = new UMImage(activity, thumb_url);
            } else {
                uMImage = new UMImage(activity, (int) R.drawable.ic_default);
            }
            UMImage uMImage2 = uMImage;
            if (shareType != 0) {
                if (shareType != 1) {
                    if (shareType != 2) {
                        if (shareType == 3) {
                            shareUrlByUmeng(activity, title, title, url, uMImage2, shareType);
                            return;
                        } else if (shareType == 4) {
                            shareUrlByUmeng(activity, title, content + " " + url, url, uMImage2, shareType);
                            return;
                        } else if (shareType != 7) {
                            if (shareType != 9) {
                                return;
                            }
                            ((ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE))
                                    .setPrimaryClip(ClipData.newPlainText(null, url));
                            App.getContext().showMessage(R.string.toast_link_copy);
                            return;
                        } else {
                            shareOthers(activity, buildTextIntent(title, content + " " + url));
                            return;
                        }
                    }
                }
                shareUrlByUmeng(activity, title, content, url, uMImage2, shareType);
            }
            Tencent.setIsPermissionGranted(true);
            shareUrlByUmeng(activity, title, content, url, uMImage2, shareType);
        }
    }

    public static void shareToWeixin(Bitmap b, boolean bCircle) {
        WXMediaMessage wXMediaMessage = new WXMediaMessage();
        wXMediaMessage.mediaObject = new WXImageObject(b);
        wXMediaMessage.thumbData = BitmapHelper.bitmapToByteArray(BitmapHelper.shrinkBitmap(b, 100), true);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction(SocialConstants.PARAM_IMG_URL);
        req.message = wXMediaMessage;
        req.scene = bCircle ? 1 : 0;
        App.getContext().wxapi.sendReq(req);
    }

    private static String buildTransaction(final String type) {
        if (type == null) {
            return String.valueOf(System.currentTimeMillis());
        }
        return type + System.currentTimeMillis();
    }

    public static void shareImageByUmeng(Activity activity, Bitmap b, IWorkout workout, int shareType) {
        if (shareType == TYPE_QQ) {
            doUmengshareWithTextAndImage(activity, null, new UMImage(activity, b), SHARE_MEDIA.QQ);
        } else if (shareType == TYPE_QZONE) {
            doUmengShareWithWeb(activity, TITLE_WORKOUT, getShareQzoneContent(workout), getShareUrl(workout),
                    new UMImage(activity, b), SHARE_MEDIA.QZONE);
        } else {
            if (shareType == TYPE_WEIBO) {
                doUmengshareWithTextAndImage(activity, getShareContent(workout), new UMImage(activity, b),
                        SHARE_MEDIA.SINA);
            }
        }
    }

    public static void shareUrlByUmeng(Activity activity, String title, String content, String url, UMImage umImage,
            int shareType) {
        SHARE_MEDIA share_media;
        if (shareType == TYPE_QQ) {
            Tencent.setIsPermissionGranted(true);
            share_media = SHARE_MEDIA.QQ;
        } else if (shareType == TYPE_QZONE) {
            share_media = SHARE_MEDIA.QZONE;
        } else if (shareType == TYPE_WECHAT) {
            share_media = SHARE_MEDIA.WEIXIN;
        } else if (shareType == TYPE_WX_CIRCLE) {
            share_media = SHARE_MEDIA.WEIXIN_CIRCLE;
        } else {
            share_media = shareType != 4 ? null : SHARE_MEDIA.SINA;
        }
        SHARE_MEDIA share_media2 = share_media;
        if (share_media2 != null) {
            doUmengShareWithWeb(activity, title, content, url, umImage, share_media2);
        }
    }

    private static void doUmengshareWithTextAndImage(final Activity activity, String text, UMImage image,
            SHARE_MEDIA shareMedia) {
        ShareAction platform = new ShareAction(activity).setPlatform(shareMedia);
        if (!TextUtils.isEmpty(text)) {
            platform.withText(text);
        }
        if (image != null) {
            platform.withMedia(image);
        }
        processShareAction(activity, platform);
    }

    private static void doUmengShareWithWeb(final Activity activity, String title, String description, String url,
            UMImage thumb, SHARE_MEDIA shareMedia) {
        ShareAction platform = new ShareAction(activity).setPlatform(shareMedia);
        UMWeb uMWeb = new UMWeb(url);
        if (!TextUtils.isEmpty(title)) {
            uMWeb.setTitle(title);
        }
        if (thumb != null) {
            uMWeb.setThumb(thumb);
        }
        if (!TextUtils.isEmpty(description)) {
            uMWeb.setDescription(description);
        }
        platform.withMedia(uMWeb);
        processShareAction(activity, platform);
    }

    private static void doShareLushuCollectionsWithMin(final Activity activity, String title, String description,
            String url, UMImage imageLocal) {
        doUmentShareWithMin(activity, title, description, url, Constants.WECHAT_MIN_PATH_LUSHU_COLLECTIONS,
                Constants.WECHAT_MIN_ID, imageLocal, SHARE_MEDIA.WEIXIN);
    }

    private static void doUmentShareWithMin(final Activity activity, String title, String description, String url,
            String path, String userName, UMImage imageLocal, SHARE_MEDIA shareMedia) {
        ShareAction platform = new ShareAction(activity).setPlatform(shareMedia);
        UMMin uMMin = new UMMin(url);
        if (imageLocal != null) {
            uMMin.setThumb(imageLocal);
        }
        if (!TextUtils.isEmpty(title)) {
            uMMin.setTitle(title);
        }
        if (!TextUtils.isEmpty(description)) {
            uMMin.setDescription(description);
        }
        uMMin.setPath(path);
        uMMin.setUserName(userName);
        platform.withMedia(uMMin);
        processShareAction(activity, platform);
    }

    private static void processShareAction(final Activity activity, ShareAction shareAction) {
        if (shareAction == null) {
            return;
        }
        shareAction.setCallback(new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                Log.i("share", "onResult -----" + share_media);
                if (SHARE_MEDIA.QQ != share_media) {
                    Toast.makeText(activity, R.string.toast_share_success, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable th) {
                Log.e("share", "onError -----" + share_media, th);
                if (SHARE_MEDIA.QQ != share_media) {
                    Toast.makeText(activity, R.string.toast_share_failed, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {
                Log.i("share", "onCancel -----" + share_media);
                if (SHARE_MEDIA.QQ != share_media) {
                    Toast.makeText(activity, R.string.toast_share_canceled, Toast.LENGTH_SHORT).show();
                }
            }
        });
        shareAction.share();
    }

    public static void shareOthers(Activity activity, Intent intent) {
        if (intent == null) {
            return;
        }
        try {
            activity.startActivity(Intent.createChooser(intent, "分享"));
        } catch (Exception unused) {
            App.getContext().showMessage("没有可以分享的应用。");
        }
    }

    public static void saveToLocal(Context context, Bitmap bitmap, String dstDir, String newFileName) {
        if (bitmap == null || dstDir == null || newFileName == null) {
            return;
        }
        try {
            CommonUtil.refreshGallery(context, AppFileUtils.saveBitmapToDCIM(context, bitmap, newFileName), newFileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Intent buildTextIntent(String title, String content) {
        Intent intent = new Intent("android.intent.action.SEND");
        intent.setType("text/plain");
        intent.putExtra("android.intent.extra.SUBJECT", title);
        intent.putExtra("android.intent.extra.TEXT", content);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return intent;
    }

    private static String buildBaseShareContent(IWorkout workout, boolean bQzone) {
        if (workout != null) {
            String sportType = getSportType(workout);
            double distance = workout.getDistance() / 1000.0d;
            String format = DateUtil.format(workout.getDuration() * 1000, 2);
            double distance2 = workout.getDuration() == 0 ? Utils.DOUBLE_EPSILON
                    : (workout.getDistance() / workout.getDuration()) * 3.6d;
            return MessageFormat.format(bQzone ? CONTENT_DETAIL_QZONE : CONTENT_DETAIL, sportType, distance, format,
                    distance2, String.valueOf(workout.getCalorie() / 1000));
        }
        return CONTENT_SIMPLE;
    }

    private static String getShareContent(IWorkout workout) {
        String buildBaseShareContent = buildBaseShareContent(workout, false);
        if (workout != null && workout.getServerId() > 0) {
            return buildBaseShareContent + CONTENT_URL_ROUTE + workout.getServerId();
        }
        return buildBaseShareContent + CONTENT_URL;
    }

    private static String getShareQzoneContent(IWorkout workout) {
        String buildBaseShareContent = buildBaseShareContent(workout, true);
        if (workout != null && workout.getServerId() > 0) {
            return buildBaseShareContent + CONTENT_URL_ROUTE + workout.getServerId();
        }
        return buildBaseShareContent + CONTENT_URL;
    }

    private static String getShareUrl(IWorkout workout) {
        if (workout != null && workout.getServerId() > 0) {
            return BASE_URL_ROUTE + workout.getServerId();
        }
        return BASE_URL;
    }

    private static String getSportType(IWorkout workout) {
        int sport = workout.getSport();
        return sport != Workout.TYPE_WALKING
                ? sport != Workout.TYPE_RUNNING ? sport != Workout.TYPE_CYCLING ? TYPE_DEFAULT : TYPE_CYCLING
                        : TYPE_RUNNING
                : TYPE_WALKING;
    }

    public static void refreshGallery(String fileName, Context context) {
        refreshGallery(fileName, context, false);
    }

    public static void refreshGallery(String fileName, Context context, boolean delete) {
        if (!delete) {
            try {
                ContentValues contentValues = new ContentValues();
                contentValues.put("_data", fileName);
                String str = "image/png";
                if (fileName.toLowerCase().endsWith("jpg")) {
                    str = "image/jpg";
                } else if (fileName.toLowerCase().endsWith("jpeg")) {
                    str = "image/jpeg";
                }
                contentValues.put("mime_type", str);
                context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            } catch (Exception unused) {
            }
        }
        try {
            File file = new File(fileName);
            Intent intent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
            intent.setData(Uri.fromFile(file));
            context.sendBroadcast(intent);
        } catch (Exception ignored) {
        }
    }
}